package org.taobao.ibatiside.ui.wizard;

import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.ProjectScope;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.Platform;
import org.eclipse.core.runtime.preferences.IEclipsePreferences;
import org.eclipse.jface.wizard.IWizardPage;
import org.eclipse.jface.wizard.Wizard;
import org.eclipse.swt.widgets.Composite;
import org.taobao.ibatiside.db.DTPFacadeImpl;
import org.taobao.ibatiside.db.IDTPFacade;
import org.taobao.ibatiside.ui.Activator;
import org.taobao.ibatiside.ui.pref.BatisProjectSettingPage;
import org.taobao.ibatiside.ui.util.MiscHelper;

public abstract class BatisCommonWizard extends Wizard implements PropertyChangeListener {
	protected IDTPFacade dtpFacade;
	protected BatisSettingModel model;
	public BatisCommonWizard() {
		super();
		model = BatisSettingModel.newInstance();
		MiscHelper.RENAME_SEED.set(0);
		model.addPropertyChangeListener(BatisSettingModel.K_CONFIGURATION_FILE, this);
	}
	@Override
	public void propertyChange(PropertyChangeEvent evt) {
		if (BatisSettingModel.K_CONFIGURATION_FILE.equals(evt.getPropertyName())){
			IFile new_config = (IFile) evt.getNewValue();
			if (new_config == null) return;
			List<URL> do_tpls = new ArrayList<URL>();
			List<URL> dao_api_tpls  = new ArrayList<URL>();
			List<URL> dao_impl_tpls = new ArrayList<URL>();
			List<URL> spring_tpls = new ArrayList<URL>();
			IProject project = new_config.getProject();
			IEclipsePreferences node = new ProjectScope(project).getNode(Activator.PLUGIN_ID);
			String tpl_src = node.get(BatisProjectSettingPage.TEMPLATES_SRC, "");
			if (StringUtils.isNotBlank(tpl_src)){
				IFolder folder = (IFolder) project.findMember(tpl_src);
				if (folder != null && folder.isAccessible()){
					try {
						IResource[] members = folder.members(IResource.FILE);
						for (IResource resource : members){
							if (resource.isAccessible()){
								if (MiscHelper.DAO_API_PATTERN.matcher(resource.getName()).matches()){
									dao_api_tpls.add(resource.getLocationURI().toURL());
								}else if (MiscHelper.DAO_IMPL_PATTERN.matcher(resource.getName()).matches()){
									dao_impl_tpls.add(resource.getLocationURI().toURL());
								}else if (MiscHelper.DATAOBJECT_PATTERN.matcher(resource.getName()).matches()){
									do_tpls.add(resource.getLocationURI().toURL());
								}else if (MiscHelper.SPRING_PATTERN.matcher(resource.getName()).matches()){
									spring_tpls.add(resource.getLocationURI().toURL());
								}
							}
						}
					} catch (CoreException e) {
						e.printStackTrace();
					} catch (MalformedURLException e) {
						e.printStackTrace();
					}
				}
			}
			
			//Workbench?? omit 
			
			//default?
			Enumeration<URL> entries = Platform.getBundle("org.taobao.ibatiside.core").findEntries(MiscHelper.DEFAULT_TEMPLATES_LOC_PATH, "*jet",false);
			while (entries.hasMoreElements()){
				URL url = entries.nextElement();
				String fn = url.getFile().substring(url.getFile().lastIndexOf('/')+1);
				if (MiscHelper.DAO_API_PATTERN.matcher(fn).matches()){
					dao_api_tpls.add(url);
				}else if (MiscHelper.DAO_IMPL_PATTERN.matcher(fn).matches()){
					dao_impl_tpls.add(url);
				}else if (MiscHelper.DATAOBJECT_PATTERN.matcher(fn).matches()){
					do_tpls.add(url);
				}else if (MiscHelper.SPRING_PATTERN.matcher(fn).matches()){
					spring_tpls.add(url);
				}
			}
			
			model.setBeanTemplates(do_tpls);
			model.setDaoInterfaceTemplates(dao_api_tpls);
			model.setDaoImplTemplates(dao_impl_tpls);
			model.setSpringTemplates(spring_tpls);
		}
	}
	
	@Override
	public void dispose() {
		model.removePropertyChangeListener(BatisSettingModel.K_CONFIGURATION_FILE,this);
		super.dispose();
	}
	public BatisSettingModel getModel() {
		return model;
	}
	@Override
	public void createPageControls(Composite pageContainer) {
		super.createPageControls(pageContainer);
		IWizardPage[] pages_hook = getPages();
		for (int i = 0; i < pages_hook.length; i++) {
			  //event fire order: control first, then page
	          model.addPropertyChangeListener((BatisCommonPage)pages_hook[i]);
		}
		refireEvent();
	}
	protected void refireEvent() {
		if (StringUtils.isNotBlank(model.getOpSql())){
			model.firePropertyChange(BatisSettingModel.K_OP_SQL, null, model.getOpSql());
		}
		if (model.getConfigurationFile() != null){
			model.firePropertyChange(BatisSettingModel.K_CONFIGURATION_FILE, null, model.getConfigurationFile());
			if (model.getSqlmapFile() != null){
				model.firePropertyChange(BatisSettingModel.K_SQLMAP_FILE, null, model.getSqlmapFile());
			}
			if (model.getDaoInterfacePath() !=null){
				model.firePropertyChange(BatisSettingModel.K_DAO_INTERFACE_PATH, null, model.getDaoInterfacePath());
			}
			if (model.getDaoImplementationPath() != null){
				model.firePropertyChange(BatisSettingModel.K_DAO_IMPLEMENTATION_PATH, null, model.getDaoImplementationPath());
			}
			
		}
	}
	
	@Override
	public void addPage(IWizardPage page) {
		super.addPage(page);
	}
	public IDTPFacade getDtpFacade() {
		if (null == dtpFacade)
			dtpFacade = new DTPFacadeImpl();
		return dtpFacade;
	}
}
